package com.tjx.mapper;

import com.tjx.entity.Coupon;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tjx.entity.CouponUser;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * <p>
 * 优惠券表 Mapper 接口
 * </p>
 *
 * @author tjx
 * @since 2025-10-29
 */
@Mapper
public interface CouponMapper extends BaseMapper<Coupon> {
        /**
         * 查询优惠券详情
         */
        @Select("select * from coupon where coupon_id = #{couponId}")
        Coupon couponQueryDetail(String couponId);

        /**
         * 扣减库存
         */
        @Update("UPDATE coupon " +
                "SET remaining_stock = remaining_stock - 1, version = version + 1 " + // 版本号自增（无需手动传新版本）
                "WHERE coupon_id = #{couponId} " +
                "AND remaining_stock > 0 " + // 兜底库存校验
                "AND version = #{oldVersion}") // 核心：校验数据库版本是否等于旧版本
        Integer couponDeductStock( String couponId, Integer oldVersion);

        /***
         * 新增用户领取记录
         */
        @Insert("INSERT INTO user_coupon (user_id, coupon_id, coupon_code) " +
                "VALUES (#{userId}, #{couponId}, #{couponCode})")
        int insertUserCoupon(CouponUser couponUser);

}
